package cn.com.yusys.yusp.admin.security;

import cn.com.yusys.yusp.commons.config.ApplicationProperties;
import cn.com.yusys.yusp.uaa.security.UaaRedisTokenStore;
import cn.com.yusys.yusp.uaa.security.UaaWebResponseExceptionTranslator;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;

import java.security.KeyPair;

/**
 * UAA配置
 *
 * @since 1.0.0
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationConfiguration extends AuthorizationServerConfigurerAdapter {
    private static final Logger logger = LoggerFactory.getLogger(AuthorizationConfiguration.class);

    @Autowired
    private RedisConnectionFactory connectionFactory;

    @Autowired
    @Qualifier("authenticationManagerBean")
    private AuthenticationManager authenticationManager;


    /**
     * Token在Redis数据库中的超时时间, 单位：分钟
     */
    @Value("${uaa.token.timeout:30}")
    private int tokenTimeout;


    /**
     * Refresh Token在Redis数据库中的超时时间, 单位：分钟
     */
    @Value("${uaa.refresh-token.timeout:40}")
    private int refreshTokenTimeout;

    /**
     * JWTAccessToken转换类全限定名
     */
    @Value("${uaa.auth.jwt-access-token-converter-class:cn.com.yusys.yusp.uaa.security.jwt.YuspJwtAccessTokenConverter}")
    private String uaaAuthJwtAccessTokenConverterClass;

    /**
     * JWT签名算法配置之keystore.jks的文件路径，相对于src/main/resources目录的地址
     */
    @Value("${uaa.jwt-keystore.path:keystore.jks}")
    private String uaaJwtKeystorePath;

    /**
     * JWT签名算法配置之keystore.jks的访问密码
     */
    @Value("${uaa.jwt-keystore.password:password}")
    private String uaaJwtKeystorePassword;

    /**
     * JWT签名算法配置之keystore.jks别名
     */
    @Value("${uaa.jwt-keystore.key-pair-name:selfsigned}")
    private String uaaJwtKeystoreKeyPairName;
    
    @Bean
    public UaaRedisTokenStore uaaTokenStore() {
        return new UaaRedisTokenStore(connectionFactory);
    }
    
    @Autowired
    PasswordEncoder passwordEncoder;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("web_app").scopes("openid").secret(passwordEncoder.encode(""))
                .authorizedGrantTypes("implicit", "refresh_token", "password", "authorization_code");

    }

    @Bean
    public WebResponseExceptionTranslator webResponseExceptionTranslator() {
        return new UaaWebResponseExceptionTranslator();
    }

    /**
     * 设置Token超时
     *
     * @return DefaultTokenServices
     */
    @Bean
    public DefaultTokenServices defaultTokenServices() {
        DefaultTokenServices tokenServices = new DefaultTokenServices();
        tokenServices.setTokenStore(uaaTokenStore());
        tokenServices.setAccessTokenValiditySeconds(this.tokenTimeout * 60);
        // 如果用户设置的refresh token的时长小于token的则默认加10分钟
        if (this.refreshTokenTimeout <= this.tokenTimeout) {
            this.refreshTokenTimeout = this.tokenTimeout + 10;
        }
        tokenServices.setRefreshTokenValiditySeconds(this.refreshTokenTimeout * 60);
        tokenServices.setSupportRefreshToken(true);
        tokenServices.setTokenEnhancer(jwtAccessTokenConverter());
        // 不允许重复使用刷新token
        tokenServices.setReuseRefreshToken(false);
        return tokenServices;
    }


    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager).tokenServices(defaultTokenServices())
                .exceptionTranslator(webResponseExceptionTranslator());
    }

    /**
     * 创建JWT转换类
     * <p>
     * 您也可以自定义JWT转换类，这需要您在应用的配置中添加您的JWT转换类的全限定名
     *
     * @return JwtAccessTokenConverter
     * @see UaaConfiguration#uaaAuthJwtAccessTokenConverterClass
     */
    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter converter = null;
        try {
            // 获取用户配置的Token转换类
            converter = (JwtAccessTokenConverter) Class.forName(this.uaaAuthJwtAccessTokenConverterClass).newInstance();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("Failed to initialize JWTToken conversion class: {}", e.getMessage());
        }
        if (converter != null) {
            KeyPair keyPair = new KeyStoreKeyFactory(new ClassPathResource(uaaJwtKeystorePath), uaaJwtKeystorePassword.toCharArray())
                    .getKeyPair(uaaJwtKeystoreKeyPairName);
            converter.setKeyPair(keyPair);
        }
        return converter;
    }

    /*
     * @Bean public JwtTokenStore jwttokenStore() { return new
     * JwtTokenStore(jwtAccessTokenConverter()); }
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");
    }

    @EnableResourceServer
    public static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

        private final TokenStore tokenStore;
        private ApplicationProperties applicationProperties;
        
        public ResourceServerConfiguration(TokenStore tokenStore,ApplicationProperties applicationProperties) {
            this.tokenStore = tokenStore;
            this.applicationProperties = applicationProperties;
        }

        @Override
        public void configure(HttpSecurity http) throws Exception {
            http.headers().contentTypeOptions().disable();
            ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry httpSecurity = http
                .csrf()
                .disable()
                .headers()
                .frameOptions()
                .disable()
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)

                .and()
                .authorizeRequests();

            // 白名单
            if (applicationProperties.getSecurity().getResource().getPermit() != null) {
                applicationProperties.getSecurity().getResource().getPermit().forEach(url -> {
                    if (!StringUtils.isEmpty(url)) {
                        httpSecurity.antMatchers(url).permitAll();
                        logger.info("添加白名单：{}成功！", url);
                    }
                });
            }
            // 黑名单
            if (applicationProperties.getSecurity().getResource().getAuthenticated() != null) {
                applicationProperties.getSecurity().getResource().getAuthenticated().forEach(url -> {
                    if (!StringUtils.isEmpty(url)) {
                        httpSecurity.antMatchers(url).authenticated();
                        logger.info("添加黑名单：{}成功！", url);
                    }
                });
            }
            httpSecurity.anyRequest().permitAll();
        }

        
        @Override
        public void configure(ResourceServerSecurityConfigurer resources) {
            resources.resourceId("uaa").tokenStore(tokenStore);
        }
    }
}
